﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;

namespace Bots.Index
{
    public class IndexEntity : DomainObject
    {
        private string objectName;
        private long indexId;
        private bool isIndexed = false;

        public IndexEntity() { }
        public IndexEntity(long id) : base(id) { }


        public String ObjectName { get { return objectName; } set { objectName = value; } }
        public long IndexID { get { return indexId; } set { this.indexId = value; } }

        public bool IsIndexed { get { return isIndexed; } set { this.isIndexed = value; } }
    }

    public class DatabaseIncIndexProvider : IncIndexProvider
    {
        private log4net.ILog logger = log4net.LogManager.GetLogger(typeof(DatabaseIncIndexProvider));
        
        static private Hashtable finders = new Hashtable();
        private static bool isRegistered = false;

        static private void RegisterFinders()
        {
            if (isRegistered) return;
            for (int i = 0; i < SearchConfig.DomainObjectFinders.Count; i++) {
                string key = SearchConfig.DomainObjectFinders.Keys[i];
                string val = SearchConfig.DomainObjectFinders[i];
                if (!finders.Contains(key))
                {
                    finders.Add(key, Activator.CreateInstance(Type.GetType(val)));
                }
            }
            isRegistered = true;
        }

        public override void IncIndexAdd(DomainObject domainObject)
        {
            IndexEntity entity = ToIndexEntity(domainObject);
            SqlConnection connection = null;
            try
            {
                string connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
                connection = new SqlConnection(connectionString);
                connection.Open();
                SqlCommand cmd = new SqlCommand("AddIndex", connection);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add(CreateInputParam("@IndexId", SqlDbType.NVarChar, entity.IndexID));
                cmd.Parameters.Add(CreateInputParam("@ObjectName", SqlDbType.NVarChar, domainObject.GetType().Name));
                cmd.Parameters.Add(CreateInputParam("@ObjectStatue", SqlDbType.SmallInt, entity.ObjectStatue));
                cmd.ExecuteNonQuery();
            }
            catch (Exception e1)
            {
                logger.Fatal(e1);
                throw e1;
            }
            finally
            {
                if (connection != null)
                {
                    connection.Close();
                }
            }
        }

        private IndexEntity ToIndexEntity(DomainObject domainObject)
        {
            IndexEntity entity = new IndexEntity();
            entity.IndexID = domainObject.ID;
            entity.ObjectName = domainObject.GetType().Name;
            entity.ObjectStatue = domainObject.ObjectStatue;
            return entity;
        }

        private SqlParameter CreateInputParam(string paramName, SqlDbType dbType, object objValue)
        {
            SqlParameter parameter1 = new SqlParameter(paramName, dbType);
            if (objValue == null)
            {
                parameter1.IsNullable = true;
                parameter1.Value = DBNull.Value;
                return parameter1;
            }
            parameter1.Value = objValue;
            return parameter1;
        }

        public override void IncIndexAdd(DomainObject[] domainObjects)
        {
            for (int i = 0; i < domainObjects.Length; i++) {
                IncIndexAdd(domainObjects[i]);
            }
        }

        public override List<DomainObject> FetchIncIndicex(int maxCount)
        {
            RegisterFinders();

            Finder finder = new IndexFinder();
            List<DomainObject> domainObjects = finder.FindByWhere("IsIndexed = 0 order by objectName");
            if (domainObjects.Count == 0)
            {
                return new List<DomainObject>();
            }

            //Get indeces list
            List<DomainObject> list = new List<DomainObject>();
            foreach (IndexEntity obj in domainObjects)
            {
                finder = finders[obj.ObjectName] as Finder;
                DomainObject domainObject = finder.FindByID(obj.IndexID);
                if (domainObject.IsEmpty()) {
                    domainObject.ID = obj.IndexID;
                }
                domainObject.ObjectStatue = obj.ObjectStatue;
                list.Add(domainObject);
            }

            IndecesUpdate(domainObjects.ToArray());
            return list;
        }

        private void IndecesUpdate(DomainObject[] domainObjects)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < domainObjects.Length; i++) {
                sb.Append(domainObjects[i].ID.ToString());
                sb.Append(",");
            }
            string ids = sb.ToString().Substring(0, sb.ToString().Length - 1);
            SqlConnection connection = null;
            try
            {
                string cmdText = "update [index] set IsIndexed=1 where ID in ({0})";
                string connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
                connection = new SqlConnection(connectionString);
                connection.Open();
                SqlCommand cmd = new SqlCommand(string.Format(cmdText, ids), connection);
                cmd.CommandType = CommandType.Text;
                cmd.ExecuteNonQuery();
            }
            catch (Exception e1)
            {
                logger.Fatal(e1);
            }
            finally
            {
                if (connection != null)
                {
                    connection.Close();
                }
            }
        }
    }
}
